<template>
  <el-dialog
    :visible.sync="visible"
    :close-on-click-modal="false"
    fullscreen
    @close="close"
  >
    <div slot="title" class="align-cm">
      {{ rfInfo == null ? '新增' : '报表：' + _.get(rfInfo, '报表title', '') }}
      <!-- {{ _.get(rfInfo,'','') }} -->
    </div>

    <div class="dig">
      <div class="abs-l">
        <div class="headArea"></div>
        <WxMsg class="bodyArea" :msgList="Lo_MsgList">
          <div slot="suffix" slot-scope="scope">
            <el-button
              type="warning"
              size="mini"
              @click="moveRight($event, scope.data)"
              :disabled="scope.data.isInRight"
            >
              向右添加
              <i class="fa fa-fw fa-long-arrow-right"></i>
            </el-button>
          </div>
        </WxMsg>

        <div class="footArea dis-flex flex-sbc" ref="pag">
          <el-button type="danger" size="mini" @click="moveRightAll"
            >全右移
            <i class="fa fa-fw fa-angle-double-right"></i>
          </el-button>

          <!-- prettier-ignore -->
          <el-pagination
            @size-change="handleSizeChange($event,ajaxLeftMsgs);"
            @current-change="handleCurrentChange($event,ajaxLeftMsgs);"
            :current-page="page.current"
            :page-sizes="page.sizes"
            :page-size="page.size"
            layout="total, prev, pager, next, jumper"
            :total="page.total">
          </el-pagination>
        </div>
      </div>
      <div class="abs-r">
        <div class="headArea">
          <el-input
            v-model="rfTitle"
            v-if="rfInfo == null"
            maxlength="30"
            show-word-limit
          >
            <template slot="prepend"> <b class="text-red">*</b>标题</template>
          </el-input>
        </div>

        <WxMsg class="bodyArea" :msgList="Ro_MsgList">
          <div slot="suffix" slot-scope="scope">
            <el-button
              type="warning"
              size="mini"
              @click="moveLeft($event, scope.data)"
            >
              <i class="fa fa-fw fa-long-arrow-left"></i>
              向左移动
            </el-button>
          </div>
        </WxMsg>
        <pre v-if="isDev">{{ DevRightMsgs }}</pre>
        <div class="footArea"></div>
      </div>
    </div>
    <!-- {{ rfInfo }} -->
    <!-- {{ tempData }} -->
    <span slot="footer" class="dialog-footer">
      <el-button
        v-if="rfInfo == null"
        size="small"
        type="warning"
        :loading="isCreateLoading"
        @click="提交并创建()"
        >创建</el-button
      >
      <el-button size="small" @click="cancel">关闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { bus } from '@/main.js';
import { mapState, mapMutations } from 'vuex';
import pagination from '@/mixin/pagination.vue';
import tableList from '@/mixin/tableList.vue';
import aboutChat from '@/mixin/aboutChat.vue';

export default {
  name: 'statementsAudit',
  mixins: [tableList, pagination, aboutChat],
  components: {
    WxMsg: () => {
      return import('@/components/wx_messageArea.vue');
    },
  },
  data() {
    return {
      tableList: [],
      isDev: process.env.NODE_ENV == 'development',
      visible: false,
      tempData: null,
      isNew: true,
      rfTitle: '',
      rfInfo: null,
      LeftMsgs: [],
      RightMsgs: [],
      DevRightMsgs: [],
      isCreateLoading: false,
      page: {
        size: 200,
      },
    };
  },
  computed: {
    ...mapState(['dialog', 'userInfo']),
    Lo_MsgList: function() {
      let ls = this.LeftMsgs;
      let rs = this.RightMsgs.map(v => {
        return v.消息id;
      });
      return ls.map(v => {
        return Object.assign(v, {
          isInRight: rs.includes(v.消息id),
        });
      });
    },
    Ro_MsgList: function() {
      return this.RightMsgs.map(v => {
        return Object.assign(v, {});
      });
    },
  },
  filters: {
    sourceNum2Txt: n => {
      return { 0: '手动录入', 1: '微信同步' }[n];
    },
  },
  methods: {
    init: function(tempData) {
      this.visible = true;
      this.tempData = this._.get(tempData, 'userInfo', null);
      let rfInfo = this._.get(tempData, '报表', null);
      if (rfInfo != null) {
        this.rfInfo = rfInfo;
        this.rfTitle = this._.get(rfInfo, '报表title', '');
      }
      this.$nextTick(() => {
        this.ajaxLeftMsgs();
        this.ajaxRightMsgs();
      });
      return;
    },
    ajaxLeftMsgs: function() {
      let row = this.tempData;
      let params = {
        wxId: this._.get(row, 'eS_Company_Id', ''), //企业微信id
        sendId: this._.get(row, 'external_userid', ''), //发送用户id
        receiveId: this._.get(row, 'external_userid', ''), // String	否	接收用户id
        startTime: this.$moment(this._.get(row, 'addTime', '')).valueOf(), //Long	否	开始时间 ms单位（13位的时间戳）
        endTime: this.$moment().valueOf(), //Long	否	结束时间 ms单位（13位的时间戳）
        // nowTime: Long	是	当前时间10位的时间戳，以秒为单位，验证消息的时效性：当前时间的前后10分钟有效
        // sign: String	是	加密后的MD5值,（key值 + nowTime）MD5
        from: this.page.current, //Integer	是	分页参数，起始位置
        size: this.page.size, //String	是	分页参数，获取条数
        sort: 1, //1:时间正序，2：时间倒序
      };
      this.$api.会话存档同步
        .获取所有会话({}, params)
        .then(res => {
          if (res.code == 8200) {
            return Promise.resolve(res);
          } else {
            return Promise.reject(res);
          }
        })
        .then(res => {
          this.page.total = res.result.total;
          this.LeftMsgs.splice(0, this.LeftMsgs.length);

          res.result.message.forEach(item => {
            this.LeftMsgs.push(this.format(item));
          });
        })
        .catch(err => {
          console.error(err);
        })
        .finally(_ => {});
    },
    ajaxRightMsgs: function() {
      let row = this.tempData;
      let reportId = this._.get(this, 'rfInfo.报表id', false);
      if (!reportId) return;
      this.$api.报表
        .获取报表List({
          reportId: reportId,
        })
        .then(res => {
          if (res.code == 200) {
            return Promise.resolve(
              res.data.map(v => {
                return v.msgid;
              }),
            );
          }
        })
        .then(res => {
          this.DevRightMsgs = res;
          if (res.length == 0) {
            return Promise.reject();
          }
          let arr = this._.chunk(res, 99);
          return Promise.all(
            arr.map(msgIdsList => {
              return this.$api.报表.getList报表数据ByMsgId(
                {},
                {
                  wxId: this._.get(row, 'eS_Company_Id', ''), //企业微信id
                  msgIdsList: msgIdsList,
                  sort: 1,
                },
              );
            }),
          );
        })
        .then(res => {
          if (
            res.every(v => {
              return v.code == 8200;
            })
          ) {
            let arr = res.reduce((t, v, i, a) => {
              return t.concat(v.result);
            }, []);
            return Promise.resolve(arr);
          }
        })
        .then(res => {
          this.RightMsgs.splice(0, this.RightMsgs.length);
          res.forEach(item => {
            this.RightMsgs.push(this.format(item));
          });
        })
        .catch(err => {
          console.error(err);
        })
        .finally(_ => {});
    },
    moveRight: function(event, msg) {
      let $moment = this.$moment;
      let target = this.RightMsgs;
      let fun = () => {
        target.push(msg);
        target.sort((a, b) => {
          return $moment(a.发送时间).isBefore(b.发送时间) ? -1 : 1;
        });
      };
      if (this.rfInfo == null) {
        fun();
      } else {
        this.$api.报表
          .逐条添加({
            rportId: this._.get(this.rfInfo, '报表id'),
            msgid: this._.get(msg, '消息id'),
          })
          .then(res => {
            if (res.code == 200) {
              fun();
            }
          })
          .catch(err => {
            this.$message.error('添加失败');
          })
          .finally(_ => {});
      }
    },
    moveLeft: function(event, msg) {
      let target = this.RightMsgs;
      let fun = () => {
        let idx = target.findIndex(v => {
          return v.消息id === msg.消息id;
        });
        target.splice(idx, 1);
      };
      if (this.rfInfo == null) {
        fun();
      } else {
        this.$api.报表
          .逐条删除({
            rportId: this._.get(this.rfInfo, '报表id'),
            msgid: this._.get(msg, '消息id'),
          })
          .then(res => {
            if (res.code == 200) {
              fun();
            }
          })
          .catch(err => {
            this.$message.error('删除失败');
          })
          .finally(_ => {});
      }
    },
    moveRightAll: function() {
      let s = this.LeftMsgs;
      let t = this.RightMsgs;
      s.forEach(msg => {
        if (
          this._.findIndex(t, {
            消息id: msg.消息id,
          }) > -1
        ) {
          return;
        }
        this.moveRight({}, msg);
      });
    },
    提交并创建: function() {
      let userInfo = this.tempData;
      this.rfTitle = this._.trim(this.rfTitle);
      if (this._.isEmpty(this.rfTitle)) {
        this.$message.error('请输入标题');
        return;
      }
      if (this.rfTitle.length > 30) {
        this.$message.error('标题过长');
        return;
      }
      this.isCreateLoading = true;
      this.$api.报表
        .创建报表返Id(
          {},
          {
            report_Id: 0,
            company_Employee_Id: this.$store.getters['userInfo/getEmployee']
              .company_Employee_Id,
            eS_Company_Id: userInfo.eS_Company_Id,
            external_userid: userInfo.external_userid,
            title: this.rfTitle,
            checkState: 0,
            // "isComplete": true,
            // "addTime": "2023-08-29T09:40:49.722Z",
            // "editTime": "2023-08-29T09:40:49.722Z"
          },
        )
        .then(res => {
          if (res.code == 200 && res.data != '') {
            return Promise.resolve(res.data);
          }
        })
        .then(rfid => {
          let msgIdsList = this.RightMsgs.map(v => {
            return v.消息id;
          });
          return Promise.all(
            msgIdsList.map(msgid => {
              return this.$api.报表.逐条添加({
                rportId: rfid,
                msgid: msgid,
              });
            }),
          );
        })
        .then(res => {
          this.$message.success('提交并创建成功');
          this.close();
        })
        .catch(err => {
          console.error(err);
          this.$message.error('提交并创建失败');
        })
        .finally(_ => {
          this.isCreateLoading = false;
        });
    },

    close: function() {
      this.visible = false;
      this.tempData = null;
      this.rfInfo = null;
      this.rfTitle = '';
      this.RightMsgs.splice(0, this.RightMsgs.length);
      this.LeftMsgs.splice(0, this.LeftMsgs.length);
    },
    cancel: function() {
      this.close();
    },
  },
  mounted: function() {
    bus.$on('创建或修改报表', temp => {
      this.init(temp);
    });
  },
  updated: function() {},
};
</script>

<style lang="less" scoped>
.loadingPlacehold {
  height: 360px;
}
.dig {
  height: 78vh;
  position: relative;
}
@w1: 51%;
@w2: 51%;
.abs-l {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: @w2;
  border: 1px solid #ddd;
  border-radius: 16px;
}
.abs-r {
  position: absolute;
  top: 0;
  bottom: 0;
  left: @w1;
  right: 0;
  border: 1px solid #ddd;
  border-radius: 16px;
}

.h100 {
  height: 100%;
}

@hh: 36px;
@fh: 36px;
.headArea {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  height: @hh;
  line-height: @hh;
  padding: 2px 10px;
}
.bodyArea {
  position: absolute;
  top: @hh+10px;
  bottom: @fh+10px;
  left: 10px;
  right: 10px;
}
.footArea {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: @fh;
}
.text-blue {
  color: #409eff;
}
</style>
